import {
  ActionType,
  PageContainer,
  ProColumns,
  ProTable,
} from '@ant-design/pro-components';
import { Button, message, Modal, Space, Tag } from 'antd';
import React, { useRef, useState } from 'react';
import {
  addDataSource,
  deleteDataSource,
  listDataSource,
  testDataSourceConnection,
  updateDataSource,
} from '@/services/dataSourceService';
import CreateModal from './components/CreateModal';
import UpdateModal from './components/UpdateModal';

/**
 * 数据源管理页面
 */
const DataSourcePage: React.FC = () => {
  // 是否显示新建窗口
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  // 是否显示更新窗口
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<DataSourceType.DataSource>();
  const actionRef = useRef<ActionType>();

  /**
   * 删除节点
   *
   * @param row
   */
  const handleDelete = async (row: DataSourceType.DataSource) => {
    const hide = message.loading('正在删除');
    if (!row) return true;
    try {
      await deleteDataSource({
        id: row.id || 0,
      });
      hide();
      message.success('删除成功');
      actionRef.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('删除失败，' + error.message);
      return false;
    }
  };

  /**
   * 测试连接
   *
   * @param row
   */
  const handleTest = async (row: DataSourceType.DataSource) => {
    const hide = message.loading('正在测试连接');
    if (!row) return true;
    try {
      const res = await testDataSourceConnection(row);
      hide();
      if (res.data) {
        message.success('连接成功');
      } else {
        message.error('连接失败');
      }
      return true;
    } catch (error: any) {
      hide();
      message.error('测试连接失败，' + error.message);
      return false;
    }
  };

  /**
   * 表格列配置
   */
  const columns: ProColumns<DataSourceType.DataSource>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      valueType: 'index',
    },
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '类型',
      dataIndex: 'type',
      valueEnum: {
        mysql: {
          text: 'MySQL',
          status: 'Processing',
        },
        oracle: {
          text: 'Oracle',
          status: 'Default',
        },
        postgresql: {
          text: 'PostgreSQL',
          status: 'Success',
        },
        sqlserver: {
          text: 'SQL Server',
          status: 'Warning',
        },
      },
      render: (_, record) => (
        <Tag color={record.type === 'mysql' ? 'blue' : record.type === 'oracle' ? 'green' : record.type === 'postgresql' ? 'purple' : 'orange'}>
          {record.type}
        </Tag>
      ),
    },
    {
      title: '连接地址',
      dataIndex: 'url',
      ellipsis: true,
    },
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInForm: true,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space>
          <a
            key="update"
            onClick={() => {
              setCurrentRow(record);
              setUpdateModalVisible(true);
            }}
          >
            修改
          </a>
          <a
            key="test"
            onClick={() => {
              Modal.confirm({
                title: '确认',
                content: '确定要测试连接吗？',
                onOk: () => handleTest(record),
              });
            }}
          >
            测试连接
          </a>
          <a
            key="delete"
            onClick={() => {
              Modal.confirm({
                title: '确认',
                content: '确定要删除吗？',
                onOk: () => handleDelete(record),
              });
            }}
          >
            删除
          </a>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<DataSourceType.DataSource>
        headerTitle="数据源管理"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            key="1"
            type="primary"
            onClick={() => {
              setCreateModalVisible(true);
            }}
          >
            新建
          </Button>,
        ]}
        request={async (params) => {
          const res = await listDataSource({
            name: params.name,
            type: params.type,
            current: params.current,
            pageSize: params.pageSize,
          });
          if (res.data) {
            return {
              data: res.data.records || [],
              success: true,
              total: res.data.total || 0,
            };
          } else {
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        columns={columns}
      />
      <CreateModal
        visible={createModalVisible}
        onSubmit={async (values) => {
          const res = await addDataSource(values);
          if (res.data) {
            message.success('创建成功');
            setCreateModalVisible(false);
            actionRef.current?.reload();
            return true;
          } else {
            message.error('创建失败');
            return false;
          }
        }}
        onCancel={() => {
          setCreateModalVisible(false);
        }}
      />
      <UpdateModal
        visible={updateModalVisible}
        old={currentRow}
        onSubmit={async (values) => {
          const res = await updateDataSource({
            id: currentRow?.id,
            ...values,
          });
          if (res.data) {
            message.success('更新成功');
            setUpdateModalVisible(false);
            actionRef.current?.reload();
            return true;
          } else {
            message.error('更新失败');
            return false;
          }
        }}
        onCancel={() => {
          setUpdateModalVisible(false);
        }}
      />
    </PageContainer>
  );
};

export default DataSourcePage;
